<?php
/**
 * @author sparkguo
 * @date 2017-09-22  销售项目管理
 */
defined('BASEPATH') OR exit('No direct script access allowed');

class Sales extends CI_Controller
{

    function __construct()
    {
        parent::__construct();
        $this->load->model('Function_m', 'fun');
        $this->load->model('Sales_m', 'm');
        $this->load->model('Report_m','report_m');
        $this->pageSize = 20;
    }

    //项目销售报表
    public function salesProgramList()
    {

        $nowpage = $_REQUEST["pageid"];
        if ($nowpage == "") $nowpage = 1;
        //---处理where查询条件
        $where = "";
        $search_data = $this->input->get();
        $starttime_date = date("Y-m-d", strtotime('-1 month'));//默认当月1号开始查询
        $endtime_date = date('Y-m-d');
        $starttime_date = $search_data['starttime'] == '' ? $starttime_date : $search_data['starttime'];
        $endtime_date = $search_data['endtime'] == '' ? $endtime_date : $search_data['endtime'];
        $tpl_data = array('starttime' => $starttime_date, 'endtime' => $endtime_date, 'search' => $search_data);
        $this->tpl->assign($tpl_data);
        if (!empty($search_data['department'])) {
            $where .= " && department_id=" . $search_data['department'];
        }
        if (!empty($search_data['program_name'])) {
            $where .= " && program_name like '%" . $search_data['program_name'] . "%'";
        }
        $list = $this->fun->getalllist("db_sales_program", $where, $nowpage, $if_csv, $this->pageSize, $orderby);
        $pageList = $this->pagenav->page($list["total"], $nowpage, $this->pageSize);
        $this->tpl->assign("totalpage", ceil($list["total"] / $this->pageSize));
        $this->tpl->assign("total", $list["total"]);
        $this->tpl->assign("pageList", $pageList);

        $onwers = array(0); //存部门信息
        foreach ($list["list"] as $key => $program) {
            $onwers[] = $program['owner'];
            $list["list"][$key]['create_time'] = date("Y-m-d H:i:s", $program['create_time']);
        }
        $this->tpl->assign("orderlist", $list["list"]);
        $onwers_str = implode(',', $onwers);
        $onwerdata = $this->fun->getalllist("d_user", "and id in($onwers_str)", null);
        $ownerlist = array(); //存人员键值对
        foreach ($onwerdata['list'] as $key => $user) {
            $ownerlist[$user['id']] = $user['name'];
        }
        //echo $this->db->last_query();
        $result_classid = $this->fun->getClassId();//获取部门信息
        $department = array(); //存部门信息
        foreach ($result_classid as $key => $dept) {
            $department[$dept['id']] = $dept['name'];
        }
        $this->tpl->assign('ownerlist', $ownerlist);
        $this->tpl->assign("classid", $result_classid);
        $this->tpl->assign("department", $department);
        $this->tpl->display('sales/ProgramList.tpl');
    }

    public function ajaxbutton()
    {
        $action = $other = $this->input->get_post('op');
        switch ($action) {
            case "delGoods":
                $this->delGoods();
                break;
            case "delProgram":
                $this->delProgram();
                break;
            case "addprogram":
                $this->addprogram();
                break;
            case "getUserlist":
                $this->getUserlist();
                break;
            case "saleCounts":
                $this->saleCounts();
                break;
            case "getsku":
                $this->getApiGoodInfo();
                break;
            case "programSaleList":
                $this->programSaleList();
                break;
            case "saveProgram":
                $this->saveProgram();
                break;
            case "programProductList":
                $this->programProductList();
                break;
            case "programProductList":
                $this->programProductList();
                break;

            case "confirmNeed":
                $this->confirmNeed();
                break;
            case "saveNeedStore":
                $this->saveNeedStore();
                break;
            case "storeNeedDetail":
                $this->storeNeedDetail();
                break;
            case "delStroeNeed":
                $this->delStroeNeed();
                break;
            case "updateStock":
                $this->updateStock();
                break;
            case "checkNeedStock":
                $this->checkNeedStock();
                break;
            case "storeConfirmForm":
                $this->storeConfirmForm();
                break;

            case "saveClearGoods":
                $this->saveClearGoods();
                break;
            case "unSaleGoods":
                $this->unSaleGoods();
                break;
            case "getclearList":
                $this->getclearList();
                break;
            case "setGoodsClearState":
                $this->setGoodsClearState();
                break;
			 case "saveUnsgoodsClear":
                $this->saveUnsgoodsClear();
                break;
            case "doSetGoodsClearState":
                $this->doSetGoodsClearState();
                break;
            case "setClear":
                $this->setClear();
                break;
            case "updateGoodsState":
                $this->updateGoodsState();
                break;
            case "clearGoodsDetail":
                $this->clearGoodsDetail();
                break;
            case "goodsClear":
                $this->goodsClear();
                break;
            case "delClearInfo":
                $this->delClearInfo();
                break;
        }
    }

    public function delGoods()
    {
        $dataid = $this->input->get('id');
        $history_url = $_SERVER['HTTP_REFERER'];
        $this->db->query("DELETE FROM db_sales_goods WHERE id=$dataid");//删除项目商品
        echo "<script language='javascript'>location.href='$history_url';</script> ";
    }

    public function delProgram()
    {
        $dataid = $this->input->get('id');
        $history_url = $_SERVER['HTTP_REFERER'];
        $this->db->query("DELETE FROM db_sales_goods WHERE program_id=$dataid");
        $this->db->query("DELETE FROM db_sales_shop WHERE program_id=$dataid");
        $this->db->query("DELETE FROM db_sales_program WHERE id=$dataid");
        echo "<script language='javascript'>location.href='$history_url';</script> ";
    }

    public function addprogram($id = '')
    {

        $result_classid = $this->fun->getClassId();//获取部门信息
        $tpl_data['department'] = $result_classid;

        if (!empty($id)) {
            $programDetail = $this->fun->getdatabasesdetail("db_sales_program", " AND id='" . $id . "'");
            $programDetail['store_arr'] = explode(',', $programDetail['store_list']);
            $tpl_data['info'] = $programDetail;
            $ownerlist = $this->fun->getalllist("d_user", " and classid=" . $programDetail['department_id'], null, 0, 0, '', 'id,name');
            $tpl_data['ownerlist'] = $ownerlist['list'];
            $tpl_data['history_url'] = $_SERVER['HTTP_REFERER'];
        } else {
            $programDetail['store_arr'] = array('0,0');
        }
        $depts = $this->fun->getdatabaseslist("d_shop", " and del_flag =0", "id,name,platfromname");
        foreach ($depts as $key => $rs) {
            $deptsname[$rs["platfromname"]][] = $rs;
        }
        //dump($deptsname);
        $res = $deptsname;

        $shop_tpl_data['select_store_arr'] = $programDetail['store_arr'];
        $shop_tpl_data['shopname'] = $res;

        $shop_str = $this->tpl->fetch('sales/shop_str.tpl', $shop_tpl_data);
        $tpl_data['shop_data'] = $shop_str;

        $this->tpl->assign($tpl_data);
        $this->tpl->display('sales/addprogram.tpl');
    }

    public function getUserlist()
    {
        $department_id = $this->input->post('dept');
        $list = $this->fun->getalllist("d_user", " and classid=" . $department_id, null, 0, 0, '', 'id,name,classid');
        $json_data = array('state' => 1, 'data' => $list['list'], 'msg' => 'success');
        echo json_encode($json_data);
    }

    //统计项目的日销售数据
    public function saleCounts()
    {
        $programid = $this->input->get('program_id');
        $search_data = $this->input->get();
        $starttime_date = $search_data['starttime'] == '' ? $starttime_date : $search_data['starttime'];
        $endtime_date = $search_data['endtime'] == '' ? $endtime_date : $search_data['endtime'];
        $tpl_data = array('starttime' => $starttime_date, 'endtime' => $endtime_date, 'search' => $search_data);
        $programDetail = $this->fun->getdatabasesdetail("db_sales_program a left join d_user on d_user.id=a.owner", " AND a.id='" . $programid . "'", "*,a.id as id");
        $tpl_data['program'] = $programDetail;
        $shopnames = $this->input->get('shopname');
        $shopnames = trim($shopnames, ",");
        if (empty($shopnames)) {
            $shopnames = $programDetail['store_list'];
        }
        $tpl_data['shopnames'] = $shopnames;

        $sale_data = $this->getProgramSaleCount($programid, $starttime_date, $endtime_date, $shopnames);
        $sale_counts = $sale_data['order_day_list'];
        foreach ($sale_counts as $key => $rs) {
            $sale_counts[$key]['subtotal'] = $rs['subtotal'] = $rs['shipping_fee_total'] + $rs['goods_amount_total'];
            $sale_counts[$key]['subzhic'] = $rs['subzhic'] = $rs['costprice_total'] + $rs['expectfee'] + $rs['platform_fee_total'] + $rs['payfee_total'];
            $sale_counts[$key]['lirun'] = $rs['lirun'] = $sale_counts[$key]['subtotal'] - $sale_counts[$key]['subzhic'];
            if ($sale_counts[$key]['subtotal'] == 0) {
                $sale_counts[$key]['maoliv'] = 0;
            } else {
                $sale_counts[$key]['maoliv'] = round($sale_counts[$key]['lirun'] / $sale_counts[$key]['subtotal'], 4) * 100;
            }
            $sale_counts[$key]['subtotal'] = number_format($sale_counts[$key]['subtotal'], 2);
            $sale_counts[$key]['subzhic'] = number_format($sale_counts[$key]['subzhic'], 2);
            $sale_counts[$key]['lirun'] = number_format($sale_counts[$key]['lirun'], 2);
            $tpl_data['allorderAmount'] += $rs['goods_amount_total'];
            $tpl_data['allshipping_fee'] += $rs['shipping_fee_total'];
            $tpl_data['allsubtotal'] += $rs['subtotal'];
            $tpl_data['allcosprice'] += $rs['costprice_total'];
            $tpl_data['allplatformfee'] += $rs['platform_fee_total'];
            $tpl_data['allfreight'] += $rs['expectfee'];
            $tpl_data['allpayfee'] += $rs['payfee_total'];
            //$tpl_data['allorderAmount']+=$rs['subzhic'];
            $tpl_data['allsubzhic'] += $rs['subzhic'];
            $tpl_data['allnum'] += $rs['sell_total'];
            $tpl_data['allorderNum'] += $rs['order_total'];
            $tpl_data['alllirun'] += $rs['lirun'];
        }
        /*
        $tpl_data['allorderAmount'] = number_format($tpl_data['allorderAmount'], 2);
        $tpl_data['allshipping_fee'] = number_format($tpl_data['allshipping_fee'], 2);
        $tpl_data['allsubtotal'] = number_format($tpl_data['allsubtotal'], 2);
        $tpl_data['allcosprice'] = number_format($tpl_data['allcosprice'], 2);
        $tpl_data['allplatformfee'] = number_format($tpl_data['allplatformfee'], 2);
        $tpl_data['allfreight'] = number_format($tpl_data['allfreight'], 2);
        $tpl_data['allpayfee'] = number_format($tpl_data['allpayfee'], 2);
        $tpl_data['allsubzhic'] = number_format($tpl_data['allsubzhic'], 2);payship_fee_total
        $tpl_data['alllirun'] = number_format($tpl_data['alllirun'], 2);*/
        $tpl_data['day_sale_list'] = $sale_counts;
        $tpl_data['alllirunlv'] = round($tpl_data['alllirun']/($tpl_data['allorderAmount']+$tpl_data['allshipping_fee']),4)*100;;
        
        $sale_counts = $sale_data['order_goods_list'];
        foreach ($sale_counts as $key => $rs) {
            $sale_counts[$key]['subtotal'] = $rs['subtotal'] = $rs['shipping_fee_total'] + $rs['goods_amount_total'];
            $sale_counts[$key]['subzhic'] = $rs['subzhic'] = $rs['costprice_total'] + $rs['expectfee'] + $rs['platform_fee_total'] + $rs['payfee_total'];
            $sale_counts[$key]['lirun'] = $rs['lirun'] = $sale_counts[$key]['subtotal'] - $sale_counts[$key]['subzhic'];
            if ($sale_counts[$key]['subtotal'] == 0) {
                $sale_counts[$key]['maoliv'] = 0;
            } else {
                $sale_counts[$key]['maoliv'] = round($sale_counts[$key]['lirun'] / $sale_counts[$key]['subtotal'], 4) * 100;
            }
            $sale_counts[$key]['subtotal'] = number_format($sale_counts[$key]['subtotal'], 2);
            $sale_counts[$key]['subzhic'] = number_format($sale_counts[$key]['subzhic'], 2);
            $sale_counts[$key]['lirun'] = number_format($sale_counts[$key]['lirun'], 2);
            $tpl_data['gallorderAmount'] += $rs['goods_amount_total'];
            $tpl_data['gallshipping_fee'] += $rs['shipping_fee_total'];
            $tpl_data['gallsubtotal'] += $rs['subtotal'];
            $tpl_data['gallcosprice'] += $rs['costprice_total'];
            $tpl_data['gallplatformfee'] += $rs['platform_fee_total'];
            $tpl_data['gallfreight'] += $rs['expectfee'];
            $tpl_data['gallpayfee'] += $rs['payfee_total'];
            //$tpl_data['gallorderAmount']+=$rs['subzhic'];
            $tpl_data['gallsubzhic'] += $rs['subzhic'];
            $tpl_data['gallnum'] += $rs['sell_total'];
            $tpl_data['gallorderNum'] += $rs['order_total'];
            $tpl_data['galllirun'] += $rs['lirun'];
        }
        /*$tpl_data['gallorderAmount'] = number_format($tpl_data['gallorderAmount'], 2);
        $tpl_data['gallshipping_fee'] = number_format($tpl_data['gallshipping_fee'], 2);
        $tpl_data['gallsubtotal'] = number_format($tpl_data['gallsubtotal'], 2);
        $tpl_data['gallcosprice'] = number_format($tpl_data['gallcosprice'], 2);
        $tpl_data['gallplatformfee'] = number_format($tpl_data['gallplatformfee'], 2);
        $tpl_data['gallfreight'] = number_format($tpl_data['gallfreight'], 2);
        $tpl_data['gallpayfee'] = number_format($tpl_data['gallpayfee'], 2);
        $tpl_data['gallsubzhic'] = number_format($tpl_data['gallsubzhic'], 2);
        $tpl_data['galllirun'] = number_format($tpl_data['galllirun'], 2);*/
        $tpl_data['order_goods_list'] = $sale_counts;
        $sale_order_list = $this->getSaleOrderList($programid, $starttime_date, $endtime_date, $shopnames, 1, 10);
        $tpl_data["sale_order_list"] = $sale_order_list['list'];
        
        $total_arr=$this->fbaSellForDay($sale_data['sale_good_ids'],$sale_data['shop_id_str']);
        $tpl_data["order_lirunlv"]=round(($total_arr["lirun"]+$tpl_data['alllirun'])/($total_arr['goods_amount_total']+$total_arr['realfee']+
        $tpl_data['allorderAmount']+$tpl_data['allshipping_fee'])*100,2);
        $this->tpl->assign($tpl_data);
        
        
        $this->tpl->display('sales/saleCounts.tpl');
    }
    
    
    public function fbaSellForDay($sale_goods_id,$sale_shops_id){
        $pageSize=10000;
   	    $starttime =$getstarttime= $this->input->get('starttime');	//开始时间
    	$endtime   = $this->input->get('endtime');		//结束时间
        $starttime=$starttime==''?date("Y-m-d",strtotime('-1 month')):$starttime;
        $endtime=$endtime==''?date("Y-m-d"):$endtime; 
        
        if($sale_shops_id)$wherestr=" AND  shopid in($sale_shops_id)";
        if(!empty($getstarttime)){
            if($starttime!='' or $endtime!=''){
                $shop_where=$endtime!=''?"and dates between '".$starttime."' and '".$endtime."'":"and dates='".$starttime."'";
            }
            $result=$this->report_m->getProgamFBAsales($starttime,$wherestr,$endtime,$sale_goods_id);
            if(count($result['list'])>0){
                foreach($result['list'] as $key=>$res){
                    $result['list'][$key]['lvrun']=round($res['goods_amount_total']+$res['realfee']
                    -$res['costprice_total']+$res['payship_fee_total']-$res['ship_price'],2);
                    $result['list'][$key]['lirunlv']=round($result['list'][$key]['lvrun']/(($res['goods_amount_total']+$res['realfee']))*100,2);
                }
            }
            $total_arr=array(); 
            $total_arr=$result['total_data'][0];
            $total_arr["i_total"]=$total_arr["goods_amount_total"]+$total_arr["realfee"];
            $total_arr["lirun"]+=$total_arr['goods_amount_total']+$total_arr['realfee']-$total_arr['costprice_total']
            +$total_arr['payship_fee_total']-$total_arr['ship_price_total'];
            $total_arr['payship_fee_total']=abs($total_arr['payship_fee_total']);
            if($total_arr['goods_amount_total']+$total_arr['realfee']>0){
                $total_arr["lirunlv"]=round($total_arr["lirun"] /($total_arr['goods_amount_total']+$total_arr['realfee'])*100,2);  
            }
            
            
            $tpl_data['tal']=$total_arr;
            $tpl_data['list']=$result['list'];
            $tpl_data['imgdata']=array_reverse($result['list']);//array_slice($result['list'],0,30);
    		$this->tpl->assign("total", $result["total"]);
        }
        $this->tpl->assign("shopsid", $shopinfo['id']);
        $this->tpl->assign($tpl_data); 
        return $total_arr; 
    }

    /****************-------------调货代码逻辑*------------*/
    //获取项目具体订单列表
    public function getProgramSaleCount($programid, $orderDate, $end_date, $shopnames)
    {
        $program_shop_list = $this->db->get_where('db_sales_shop', "program_id=" . $programid)->result_array();
        $program_goods_list = $this->db->get_where('db_sales_goods', "program_id=" . $programid)->result_array();
        $goodids = $shopids = array();
        foreach ($program_goods_list as $key => $goodinfo) {
            $goodids[] = $goodinfo['goods_id'];
        }
        $shopnames = str_replace(",", "','", $shopnames);
        $program_shop_list = $this->db->get_where('d_shop', "name in('" . $shopnames . "')")->result_array();
        foreach ($program_shop_list as $key => $shopinfo) {
            $shopids[] = $shopinfo['id'];
        }
        if (count($goodids) < 1) {
            die("该项目下还没有添加商品，请先添加商品！");
        }
        if (count($shopids) > 0) {
            $shop_id_str = implode(',', $shopids);
            $wherestr = " && shopid in($shop_id_str)";
        }

        $goods_arr_str = implode(',', $goodids);
        $date_where = $end_date != '' ? "and dates between '" . $orderDate . "' and '" . $end_date . "'" : "and dates='" . $orderDate . "'";
        $order_day_list = $this->fun->getdatabaseslist("db_order_sell A left join db_order_list B on A.order_id=B.order_id", "$wherestr  {$date_where} AND
         order_status !=6 && goods_id in($goods_arr_str) group by dates", "*,SUM(B.goods_amount) as amount_total,sum(A.goods_number) as sell_total,
         sum(B.shipping_fee) as shipping_fee_total,sum(B.shipping_expectfee) as expectfee,SUM(A.goods_amount) as goods_amount_total,sum(platform_fee) as platform_fee_total,
        sum(pay_fee) as payfee_total,sum(costprice*goods_number) as costprice_total,count(*) as order_total,sum(goods_number) as goods_number_total");

        $order_goods_list = $this->fun->getdatabaseslist("db_order_sell A left join db_order_list B on A.order_id=B.order_id", "$wherestr  {$date_where} AND
         order_status !=6 && goods_id in($goods_arr_str) group by goods_id", "*,SUM(B.goods_amount) as amount_total,sum(A.goods_number) as sell_total,
         sum(B.shipping_fee) as shipping_fee_total,sum(B.shipping_expectfee) as expectfee,SUM(A.goods_amount) as goods_amount_total,sum(platform_fee) as platform_fee_total,
        sum(pay_fee) as payfee_total,sum(costprice*goods_number) as costprice_total,count(*) as order_total,sum(goods_number) as goods_number_total", 'order by sell_total desc');
        $result_data = array('order_day_list' => $order_day_list, 'order_goods_list' => $order_goods_list,
            'shop_id_str'=>$shop_id_str,'sale_good_ids'=>$goods_arr_str);
        
        return $result_data;
    }

    //库存报表


    public function getSaleOrderList($programid, $orderDate, $end_date, $shopnames, $pageid = 1, $pagesize = 100)
    {
        $program_goods_list = $this->db->get_where('db_sales_goods', "program_id=" . $programid)->result_array();
        $goodids = $shopids = array();
        foreach ($program_goods_list as $key => $goodinfo) {
            $goodids[] = $goodinfo['goods_id'];
        }
        $shopnames = str_replace(",", "','", $shopnames);
        $program_shop_list = $this->db->get_where('d_shop', "name in('" . $shopnames . "')")->result_array();
        foreach ($program_shop_list as $key => $shopinfo) {
            $shopids[] = $shopinfo['id'];
        }

        if (count($goodids) < 1) {
            die("该项目下还没有添加商品，请先添加商品！");
        }
        if (count($shopids) > 0) {
            $shop_id_str = implode(',', $shopids);
            $wherestr = " && shopid in($shop_id_str)";
        }
        $goods_arr_str = implode(',', $goodids);
        $date_where = $end_date != '' ? "and dates between '" . $orderDate . "' and '" . $end_date . "'" : "and dates='" . $orderDate . "'";
        $sale_order_list = $this->fun->getalllist("db_order_sell A left join db_order_list B on A.order_id=B.order_id", "$wherestr  {$date_where} AND
         order_status !=6 && goods_id in($goods_arr_str)", $pageid, 0, $pagesize, "order by dates desc", "*,A.goods_amount as goods_amount");
        return $sale_order_list;
    }

    public function programSaleList()
    {
        $nowpage = $_REQUEST["pageid"];
        if ($nowpage == "") $nowpage = 1;
        $programid = $this->input->get('program_id');
        $search_data = $this->input->get();
        $shopnames = $this->input->get('shopname');
        $starttime_date = $search_data['starttime'] == '' ? $starttime_date : $search_data['starttime'];
        $endtime_date = $search_data['endtime'] == '' ? $endtime_date : $search_data['endtime'];
        $tpl_data = array('starttime' => $starttime_date, 'endtime' => $endtime_date, 'search' => $search_data);
        $programDetail = $this->fun->getdatabasesdetail("db_sales_program a left join d_user on d_user.id=a.owner", " AND a.id='" . $programid . "'", "*,a.id as id");
        $tpl_data['program'] = $programDetail;
        $sale_order_list = $this->getSaleOrderList($programid, $starttime_date, $endtime_date, $shopnames, $nowpage);
        $tpl_data["sale_order_list"] = $sale_order_list['list'];
        $pageSize = 100;
        $pageList = $this->pagenav->page($sale_order_list["total"], $nowpage, $pageSize);
        $this->tpl->assign("totalpage", ceil($sale_order_list["total"] / $pageSize));
        $this->tpl->assign("total", $sale_order_list["total"]);
        $this->tpl->assign("pageList", $pageList);

        $this->tpl->assign($tpl_data);

        $this->tpl->display("sales/programOrderList.tpl");
    }

    function saveProgram()
    {
        //查询是否有正常传值
        $postdata = $_POST;
        $store_list = $postdata['shopID'];
        $new_stores = array();
        if (is_array($store_list)) {
            foreach ($store_list as $key => $store) {
                $storeName_val = explode('|', $store);
                $new_stores[] = $storeName_val;
                $store_names[] = $storeName_val[0];
            }
            $store_list = implode(",", $store_names);
        } else {
            $store_list = '';
            $new_stores = array();
        }
        $savedata = array(
            'program_name' => $postdata['program_name'],
            'department_id' => $postdata['department_id'],
            'owner' => $postdata['owner'],
            'store_list' => $store_list,
            'create_time' => time(),
        );
        //dump($savedata);
        if ($postdata['program_name'] == "" || $postdata['owner'] == '') {
            echo "<script language='javascript'>alert('项目名称与负责人必须填写!');history.back();</script> ";
            die;
        }
        if (!empty($postdata['id'])) {//更新数据
            $program_id = $this->m->saveProgram($savedata, $new_stores, $postdata['id']);
            echo "<script language='javascript'>alert('项目编辑成功!');location.href='$postdata[history_url]';</script> ";
        } else {
            $program_id = $this->m->saveProgram($savedata, $new_stores);
            //echo $this->db->last_query();
            echo "<script language='javascript'>alert('新增项目成功!');location.href='/sales/salesProgramList';</script> ";
        }
    }

    public function programProductList()
    {
        $programid = $this->input->get('program_id');
        $programDetail = $this->fun->getdatabasesdetail("db_sales_program", " AND id='" . $programid . "'");
        $tpl_data['info'] = $programDetail;
        $goods_data = $this->fun->getalllist("db_sales_goods a left join db_goods b on a.sku_code=b.goods_sku", " and a.program_id=" . $programid, $nowpage, $if_csv, $this->pageSize, $orderby);
        $pageList = $this->pagenav->page($goods_data["total"], $nowpage, $this->pageSize);
        $this->tpl->assign("totalpage", ceil($goods_data["total"] / $this->pageSize));
        $this->tpl->assign("total", $goods_data["total"]);
        $this->tpl->assign("pageList", $pageList);
        foreach ($goods_data["list"] as $key => $val) {
            $goods_data["list"][$key]['create_time'] = date("Y-m-d H:i", $val['create_time']);
        }
        $this->tpl->assign("goodslist", $goods_data["list"]);
        $this->tpl->assign($tpl_data);
        $this->tpl->display('sales/programProductList.tpl');
    }

    public function confirmNeed()
    {
        $storeids = $this->input->post("storeid");
        $need_store = $this->input->post("need_store");
        $good_sku = $this->input->post("good_sku");
        $goods_name = $this->input->post("goods_name");
        $two_stockid = $this->input->post("two_stockid");
        $two_stock = $this->input->post("two_stock");
        $needstores = array();
        if (count($storeids) < 1) {
            echo "<script language='javascript'>alert('请先选择要调货的商品');history.back();</script>";
            die;
        }
        foreach ($storeids as $key => $val) {
            $needstoreinfo = array('storeid' => $val, 'sku' => $good_sku[$val], 'need_store' => $need_store[$val],
                'goods_name' => $goods_name[$val], 'two_stock' => $two_stock[$val], 'two_stockid' => $two_stockid[$val]);
            $needstores[] = $needstoreinfo;
        }
        $needstore_json = json_encode($needstores);
        $adddata = array();
        $this->tpl->assign('needstore', $needstores);
        $this->tpl->assign('needstore_json', $needstore_json);
        $this->tpl->display("StoreManage/confirmNeed.tpl");
    }

    //保存项目信息

    public function saveNeedStore()
    {
        $needstore_json = $this->input->post("needstore_json");
        $adddata = array('needstore_json' => $needstore_json, 'creator' => $_COOKIE['username'], 'createtime' => date("Y-m-d H:i:s"));
        $this->db->insert('db_store_change', $adddata);
        echo "<script language='javascript'>alert('调货单数据生成成功,请前往列表打印');location.href='/sales/storeNeedList';</script>";
    }

    //获取部门下的职员

    public function storeNeedDetail()
    {
        $storeneedid = $this->input->get("needid");
        $rs = $this->fun->getdatabasesdetail("db_store_change", "AND id=" . $storeneedid);
        $needgoods = json_decode($rs['needstore_json'], true);
        $this->tpl->assign("needstore", $needgoods);
        $rs['print_time'] = date("Y-m-d H:i");
        $shop_tpl_data["info"] = $rs;
        $shop_tpl_data['needstore'] = $needgoods;
        $printr_info = $this->tpl->fetch('StoreManage/storeNeedDetail.tpl', $shop_tpl_data);
        echo $printr_info;
    }

    public function delStroeNeed()
    {
        $storeneed = $this->input->get("needid");
        $this->db->delete('db_store_change', 'id=' . $storeneed);
        $history_url = $_SERVER['HTTP_REFERER'];
        echo "<script language='javascript'>location.href='" . $history_url . "';</script>";
    }

    public function updateStock()
    {

        $storeneedid = $this->input->post("dataid");
        $rs = $this->fun->getdatabasesdetail("db_store_change", "AND action_state=0 and id=" . $storeneedid);
        $needgoods = json_decode($rs['needstore_json'], true);
        $new_arr = array();
        foreach ($needgoods as $key => $changeStore) {
            $changeStore['confirm_need'] = $_POST['one_storeid_' . $changeStore['storeid']];

            $res = $this->fun->getdatabasesdetail("db_goods_stock", "AND id=" . $changeStore['two_stockid']);
            $two_store = $res['stock'] > 0 ? $res['stock'] : 0;

            $tsavedata = array('stock' => $two_store - $changeStore['confirm_need']);
            $this->db->update('db_goods_stock', $tsavedata, 'id=' . $changeStore['two_stockid']);

            $rs = $this->fun->getdatabasesdetail("db_goods_stock", "AND id=" . $changeStore['storeid']);
            $new_one_store = $rs['stock'];//>0?$rs['stock']:0;
            $savedata = array('stock' => $new_one_store + $changeStore['confirm_need']);
            $this->db->update('db_goods_stock', $savedata, 'id=' . $changeStore['storeid']);
            $val = $changeStore;

            $addstock = array(
                'istype' => '6', 'goods_id' => $rs['goods_id'], 'goods_name' => $val['goods_name'], 'oldnum' => $rs['stock'], 'newnum' => $savedata["stock"],
                'goods_sku' => $val['sku'], 'goods_instock' => $val['need_store'], 'tostock' => 1, 'storagename' => '一号仓', 'status' => '1',
                'intime' => time(), 'oper' => $_COOKIE['userid'], 'opername' => $_COOKIE['username']
            );
            $this->db->insert("db_goods_handstorage", $addstock);
            $addstock = array(
                'istype' => '7', 'goods_id' => $rs['goods_id'], 'goods_name' => $val['goods_name'], 'oldnum' => $changeStore['two_stock'], 'newnum' => $tsavedata["stock"],
                'goods_sku' => $val['sku'], 'goods_instock' => $val['need_store'], 'tostock' => 2, 'storagename' => '二号仓', 'status' => '1',
                'intime' => time(), 'oper' => $_COOKIE['userid'], 'opername' => $_COOKIE['username']
            );
            $this->db->insert("db_goods_handstorage", $addstock);

            $rval = "更新二号仓原库存{$changeStore[two_stock]}更新为{$tsavedata[stock]}，一号仓库存$rs[stock]更新为{$savedata[stock]}";

            $this->fun->goods_update_log($rs["goods_id"], $rval, 1);    //更新商品信息
            $new_arr[] = $changeStore;
        }
        $savedata = array('action_state' => 1, 'needstore_json' => json_encode($new_arr));
        $this->db->update('db_store_change', $savedata, 'id=' . $storeneedid);
        $history_url = $_SERVER['HTTP_REFERER'];
        echo "<script language='javascript'>alert('处理完成');location.href='" . $history_url . "';</script>";
    }

    public function checkNeedStock()
    {
        $skulist = $this->input->post("goods_sku");
        $need_stock = $this->input->post("need_stock");
        $datatrue = 0;
        foreach ($skulist as $key => $val) {
            if ($val != '' && $need_stock[$key] != '') {
                $datatrue = 1;
                $have_send_arr[$val] = $need_stock[$key];
            }
            if (empty($val)) {
                unset($skulist[$key]);
            }
        }
        $goods_sku_str = implode("','", $skulist);
        if ($datatrue < 1) {
            echo "<script language='javascript'>alert('请先填写需要调货的商品及对应数量');history.back();</script>";
            die;
        }
        $where = "and a.goods_sku in('$goods_sku_str') and storage_id in(1,2)";
        $goods_list = $this->fun->getalllist('db_goods a left join db_goods_stock b on b.goods_id=a.goods_id ', $where, 1, 0, 20000,
            'order by a.goods_id desc', "b.*,a.goods_id,a.goods_sku,a.goods_name,a.dailysales");

        $newgoods = array();
        foreach ($goods_list['list'] as $key => $goodinfo) {
            $newgoods[$goodinfo['goods_id'] . "_" . $goodinfo['storage_id']] = $goodinfo;
        }
        foreach ($newgoods as $key => $info) {
            if ($info['storage_id'] == '2') {
                continue;
            }
            $sendgoodsnum = $have_send_arr[$info['goods_sku']];
            $infov['storage_name'] = '2';
            $info['two_storage_name'] = $newgoods[$info['goods_id'] . "_" . $infov['storage_name']]['storage_name'];
            $info['two_stock'] = $newgoods[$info['goods_id'] . "_" . $infov['storage_name']]['stock'];
            $sendgoodsnum = $sendgoodsnum > $info['two_stock'] ? $info['two_stock'] : $sendgoodsnum;
            $info['two_stockid'] = $newgoods[$info['goods_id'] . "_" . $infov['storage_name']]['id'];
            $info['two_positions'] = $newgoods[$info['goods_id'] . "_" . $infov['storage_name']]['positions'];
            $info['sendgoodsnum'] = $sendgoodsnum;
            $stock = $info['stock'] < 0 ? 0 : $info['stock'];
            $info['sku'] = $info['goods_sku'];
            $info['need_store'] = $sendgoodsnum;
            $success_goods[] = $info;
        }
        $needstores = array();
        if (!is_array($success_goods)) {
            $success_goods = array();
        }
        foreach ($success_goods as $key => $info) {
            $needstoreinfo = array('storeid' => $newgoods[$info['goods_id'] . "_1"]['id'], 'sku' => $info['sku'], 'need_store' => $info['need_store'],
                'goods_name' => $info['goods_name'], 'two_stock' => $info['two_stock'], 'two_stockid' => $info['two_stockid']);
            $needstores[] = $needstoreinfo;
        }
        $needstore_json = json_encode($needstores);
        $adddata = array();
        $this->tpl->assign('needstore', $success_goods);
        $this->tpl->assign('needstore_json', $needstore_json);
        $this->tpl->display("StoreManage/confirmNeed.tpl");
    }

    public function storeConfirmForm()
    {
        $storeneedid = $this->input->get("dataid");
        $rs = $this->fun->getdatabasesdetail("db_store_change", "AND id=" . $storeneedid);
        $needgoods = json_decode($rs['needstore_json'], true);
        $this->tpl->assign("needstore", $needgoods);
        $rs['print_time'] = date("Y-m-d H:i");
        $shop_tpl_data["info"] = $rs;
        $shop_tpl_data['is_finish'] = $rs['action_state'];
        $shop_tpl_data['needstore'] = $needgoods;
        $shop_tpl_data['dataid'] = $storeneedid;
        $printr_info = $this->tpl->fetch('StoreManage/storeConfirmForm.tpl', $shop_tpl_data);
        echo $printr_info;
    }

    public function saveClearGoods()
    {
		
        $formdata = $_POST;
        $needstore_json = $this->input->post("clear_goods_json");
        $cleargoods = json_decode($formdata['clear_goods_json'], true);
	

        $new_arr = array();
        $cost_price = $stock_count = 0;
        foreach ($cleargoods as $key => $info) {
            $info['confirmstock'] = $this->input->post("goodsid_" . $info['goods_id']);
            $new_arr[] = $info;
            $cost_price += $info['cost_price'] * $info['confirmstock'];
            $stock_count += $info['confirmstock'];
            $storage_name = $info['storagename'];
			$this->db->update("db_goods_clear_list",array('types'=>3),"goods_id='".$info['goods_id']."'");
        }
        $cost_price = $cost_price;
        $clear_goods_json = json_encode($new_arr);
        $adddata = array('clear_goods_json' => $clear_goods_json, 'creator' => $_COOKIE['username'], 'status' => $formdata['status'],
            'createtime' => date("Y-m-d H:i:s"), "cost_price" => $cost_price, "stock_count" => $stock_count, "storage_name" => $storage_name);

        $this->db->insert('db_goods_clear', $adddata);

        echo "<script language='javascript'>alert('申请数据保存成功,请前往列表查看');location.href='/sales/goodsClearList';</script>";
    }
	
	public function saveUnsgoodsClear()
	{
		$goodslist = $_POST['storeid'];
		foreach($goodslist as $key=>$rs){
			$goods_id = $rs;
			$rsdb =  $this->fun->getdatabasesdetail('db_goods'," AND goods_id='".$goods_id."'");
			$stock = $this->fun->getdatabasesdetail("db_goods_stock A left join db_storage B on A.storage_id = B.id "," AND goods_id IN ($goods_id) AND B.is_show = 1"," SUM(stock) as stock,positions,storage_name");
			$rsclear = $this->fun->getdatabasesdetail('db_goods_clear_list'," AND goods_id='".$goods_id."'");
			if(!$rsclear){
				$post="";
				$post["parent_id"] = $rsdb["goods_parentID"];
				$post["goods_id"] = $goods_id;
				$post["goods_sku"] = $rsdb["goods_sku"];
				$post["goods_name"] = $rsdb['goods_name'];
				$post["positions"] = $stock['positions'];
				$post["storage_name"] = $stock['storage_name'];
				$post["stock"] = $stock['stock'];
				$post["types"] = 0;
				$post["oper"] = $_COOKIE['username'];
				$post["uptime"] = time();
				$this->db->insert("db_goods_clear_list",$post);
			}
	 
		}
		  echo "<script language='javascript'>alert('申请数据保存成功,请前往列表查看');location.href='/sales/ajaxbutton?op=getclearList';</script>";
	}


    function unSaleGoods()
    {
        $this->pageSize = 100;
        $search_data = $this->input->get();
        $nowpage = $_REQUEST["pageid"];
        $limit_month = $search_data['limit_month'] == '' ? 4 : $search_data['limit_month'];
        $unsalelilv = $search_data['unsalelilv'] == '' ? 40 : $search_data['unsalelilv'];
        $search_sku = $search_data['search_sku'];
        if ($nowpage == "") $nowpage = 1;
        $limit_month_time = strtotime("-$limit_month month");
        if (!empty($unsalelilv)) {
            $where .= " && A.stock/B.newnum >0." . $unsalelilv;
        }
        if (!empty($search_sku)) {
            $where .= " && B.goods_sku like '%" . $search_sku . "%'";
        }
        if (!empty($search_data['positions'])) {
            $where .= " && A.positions like '%" . $search_data['positions'] . "%'";
        }
        $where .= " && B.istype in(1,3,6)";
        $where .= " && B.goods_id not in(select distinct goods_id from db_goods_handstorage where intime>$limit_month_time)";
		$where .= " && B.goods_id not in(select goods_id from db_goods_clear_list)";
        $where .= " && C.g_sale_status<>5  && A.stock/B.newnum <1";
        $tpl_data = array("sch_namecn" => $search_data['sch_namecn'], 'sch_name' => $search_data['sch_name'], 'limit_month' => $limit_month,
            'imit_month_date' => date("Y-m-d", $limit_month_time), 'starttime' => $starttime, 'endtime' => $endtime, 'search_sku' => $search_sku,
            'message_state' => $search_data['message_state'], 'unsalelilv' => $unsalelilv, 'positions' => $search_data['positions']);
        $list = $this->fun->getalllist("db_goods_stock A left join db_goods_handstorage B on A.goods_id=B.goods_id and A.storage_id=B.tostock
        left join db_goods C on A.goods_id=C.goods_id",
            $where, $nowpage, 0, $this->pageSize, ' group by B.goods_sku order by B.intime desc', "*,
        A.stock/B.newnum as unsalelilv,count(B.goods_sku)");//

        $totaldata = $this->fun->getdatabaseslist("db_goods_handstorage B left join db_goods_stock A on A.goods_id=B.goods_id and A.storage_id=B.tostock
        left join db_goods C on A.goods_id=C.goods_id", $where . "
         order by B.goods_sku desc", 'sum(A.stock*C.g_costprice) as total_cost_price,sum(A.stock) as total_stock');

        $datalist = $list["list"];
        $sku_list = iarray_column($datalist, 'goods_sku');
        $sku_list_str = implode("','", $sku_list);
        $goods_list = $this->fun->getdatabaseslist("db_goods", " and goods_sku in('$sku_list_str')", "goods_id,goods_sku,g_costprice");
        $costprice_list = iarray_column($goods_list, 'g_costprice', 'goods_id');
        foreach ($datalist as $key => $val) {
            $datalist[$key]['insttime'] = date("Y-m-d", $val['intime']);
            $datalist[$key]['unsalelilv'] = round($val['unsalelilv'] * 100, 2);
            $datalist[$key]['costprice'] = sprintf("%01.2f", $costprice_list[$val['goods_id']] * $val['stock']);
        }

        $pageList = $this->pagenav->page($list["total"], $nowpage, $this->pageSize);
        $this->tpl->assign($tpl_data);
        $this->tpl->assign('totaldata', $totaldata[0]);
        $this->tpl->assign("totalpage", ceil($list["total"] / $this->pageSize));
        $this->tpl->assign("datatotal", $list["total"]);
        $this->tpl->assign("pageList", $pageList);
        $this->tpl->assign("datalist", $datalist);
        $this->tpl->display("sales/unSaleGoods.tpl");
    }

    public function getclearList()
    {
        $this->pageSize = 300;
        $nowpage = $_REQUEST["pageid"];
        if ($nowpage == "")
            $nowpage = 1;
		$search_sku = trim($this->input->get('search_sku'));
		if($search_sku)
		{
			$where.=" AND goods_sku like '%".$search_sku."%'";
			$this->tpl->assign("search_sku", $search_sku);
		}
		$positions = trim($this->input->get('positions'));
		if($positions)
		{
			$cang = trim($this->input->get('cang'));
			if($cang==1)
			{
				$where.=" AND B.positions like '%".$positions."%'";
			}else{
				$where.=" AND B.positions not like '%".$positions."%'";
			}
			$this->tpl->assign("positions", $positions);
			$this->tpl->assign("cang", $cang);
		}
		$where.=" AND types=0 AND B.stock >0";
        $orderby = " order by uptime DESC";
		$if_csv = trim($this->input->get('if_csv'));
        $list = $this->fun->getalllist('db_goods_clear_list A LEFT JOIN db_goods_stock B on A.goods_id = B.goods_id  and B.storage_id in(1,2)', $where, $nowpage, $if_csv, $this->pageSize, $orderby, 'A.id,A.types,A.parent_id,A.goods_id,A.goods_sku,A.goods_name,A.oper,B.storage_name,B.stock,B.positions,A.oper,A.uptime');

        foreach ($list["list"] as $key => $rs) {
            $list["list"][$key]['uptime'] = date("Y-m-d", $rs['uptime']);
            $goods_list = $this->fun->getdatabasesdetail("db_goods", " and goods_id = {$rs[goods_id]}", "g_buyer,g_checkman,g_costprice,bulkprice,g_supplier,sales1,sales2,sales3");
           // $stock = $this->fun->getdatabasesdetail("db_goods_stock", " and goods_id = {$rs[goods_id]}", "stock,positions");
		    if($goods_list['g_supplier'] ==1 || $goods_list['g_supplier'] ==2)
			{
				 $g_costprice = $goods_list['bulkprice']?$goods_list['bulkprice']:$goods_list['g_costprice'];
			}else{
				 $g_costprice =$goods_list['g_costprice'];
			}
		   
            $list["list"][$key]['stcostprice'] = $g_costprice * $rs['stock'];
			$list["list"][$key]['positions'] = $rs['positions'];
            $list["list"][$key]['g_checkman'] = $goods_list['g_checkman'];
            $list["list"][$key]['g_buyer'] = $goods_list['g_buyer'];

			$list["list"][$key]['sales1'] = $goods_list['sales1'];
			$list["list"][$key]['sales2'] = $goods_list['sales2'];
			$list["list"][$key]['sales3'] = $goods_list['sales3'];

			$resdb = $this->db->get_one("SELECT dates from db_order_sell A LEFT JOIN db_order_list B on A.order_id = B.order_id where goods_sn  = '".$rs['goods_sku']."' AND order_status = 5  ORDER BY rec_id DESC");
			$list["list"][$key]['ordertimes'] = $resdb['dates']?$resdb['dates']:'';
        }
		
		 if($if_csv==1){
		        require dirname(__FILE__)."/../../fuman/ClassesExcel/PHPExcel.php";
		        $objExcel = new PHPExcel();
		      

		        $objExcel->setActiveSheetIndex(0);
		        $objExcel->getActiveSheet()->getDefaultRowDimension()->setRowHeight(15);
		        $objExcel->getActiveSheet()->getColumnDimension('A')->setWidth(22);
		        $objExcel->getActiveSheet()->getColumnDimension('B')->setWidth(20);
		        $objExcel->getActiveSheet()->getColumnDimension('C')->setWidth(30);
		        $objExcel->getActiveSheet()->getColumnDimension('D')->setWidth(15);
		        $objExcel->getActiveSheet()->getColumnDimension('E')->setWidth(26);
		        $objExcel->getActiveSheet()->getColumnDimension('F')->setWidth(10);
		        $objExcel->getActiveSheet()->getColumnDimension('G')->setWidth(10);
		        $objExcel->getActiveSheet()->getColumnDimension('H')->setWidth(20);
		
		        //设置标题
		        $objExcel->setActiveSheetIndex(0)->setCellValue('A1','商品编号');
		        $objExcel->setActiveSheetIndex(0)->setCellValue('B1','名称');
		        $objExcel->setActiveSheetIndex(0)->setCellValue('C1','仓库');
		        $objExcel->setActiveSheetIndex(0)->setCellValue('D1','仓位');
		        $objExcel->setActiveSheetIndex(0)->setCellValue('E1','现剩余库存');
		        $objExcel->setActiveSheetIndex(0)->setCellValue('F1','库存价值');
		        $objExcel->setActiveSheetIndex(0)->setCellValue('G1','开发/维护');
		        $objExcel->setActiveSheetIndex(0)->setCellValue('H1','采购人员');
				$count = 0;
		        foreach($list["list"] as $k=>$v){
			      
			        $count = $k+2;
			        $objExcel->setActiveSheetIndex(0)->setCellValue('A'.$count,$v['goods_sku']);
			        $objExcel->setActiveSheetIndex(0)->setCellValue('B'.$count,$v['goods_name']);
			        $objExcel->setActiveSheetIndex(0)->setCellValue('C'.$count,$v['storage_name']);
			        $objExcel->setActiveSheetIndex(0)->setCellValue('D'.$count,$v['positions']);
			        $objExcel->setActiveSheetIndex(0)->setCellValue('E'.$count,$v['stock']);
			        $objExcel->setActiveSheetIndex(0)->setCellValue('F'.$count,$v['stcostprice']);
			        $objExcel->setActiveSheetIndex(0)->setCellValue('G'.$count,$v['g_checkman']);
			        $objExcel->setActiveSheetIndex(0)->setCellValue('H'.$count,$v['g_buyer']);
			     
		        }
		        $excel_name = date("YmdHis");
		        header("Content-type:application/vnd.ms-excel;charset=gb2312");
		        header('Content-Disposition: attachment;filename="'.$excel_name.'.xls"');
		        header('Cache-Control: max-age=0');
		        $objWriter = PHPExcel_IOFactory::createWriter($objExcel, 'Excel5');
		        $objWriter->save('php://output');
		        exit;


	        }

        $pageList = $this->pagenav->page($list["total"], $nowpage, $this->pageSize);
        $this->tpl->assign("totalpage", ceil($list["total"] / $this->pageSize));
        $this->tpl->assign("total", $list["total"]);
        $this->tpl->assign("pageList", $pageList);
        $this->tpl->assign("list", $list["list"]);
        $this->tpl->display("sales/getclearList.tpl");
    }

    public function setGoodsClearState()
    {
        $storeneedid = $this->input->get("dataid");
        $rs = $this->fun->getdatabasesdetail("db_goods_clear", "AND id=" . $storeneedid);
        $needgoods = json_decode($rs['clear_goods_json'], true);
        $this->tpl->assign("goodslist", $needgoods);
        $rs['print_time'] = date("Y-m-d H:i");
        $shop_tpl_data["info"] = $rs;
        $shop_tpl_data['is_finish'] = $rs['action_state'];
        $shop_tpl_data['needstore'] = $needgoods;
        $shop_tpl_data['dataid'] = $storeneedid;
        $printr_info = $this->tpl->fetch('sales/setGoodsClearState.tpl', $shop_tpl_data);
        echo $printr_info;
    }

    public function doSetGoodsClearState()
    {
		
        $formdata = $this->input->post();
        $res = $this->fun->getdatabasesdetail("db_goods_clear", "AND id=" . $formdata['dataid']);
        $cleargoods = json_decode($res['clear_goods_json'], true);

		
        $new_arr = array();
        $cost_price = $stock_count = 0;
	
        foreach ($cleargoods as $key => $info) {
            $info['confirmstock'] = $this->input->post("goodsid_" . $info['goods_id']);
			if($info['confirmstock']>0){	//盘点库存为0
				$new_arr[] = $info;
				$cost_price += $info['cost_price'] * $info['confirmstock'];
				$stock_count += $info['confirmstock'];
				$storage_name = $info['storagename'];
			}
			
			if($info['confirmstock']==0){
				$stock_str  = "清仓盘点 将{$info[storagename]}库存[$info[stock]]更新为[{$info[confirmstock]}]";
				$this->fun->goods_update_log($info["goods_id"], $stock_str, 1);
				$this->db->update("db_goods_stock", array("stock" => $info["confirmstock"]), "storage_id={$info[storage_id]} and goods_id=" . $info["goods_id"]);
				$this->db->update("db_goods",  array("g_sale_status" => 5), "goods_id=" . $info["goods_id"]);
				$this->db->delete('db_goods_clear_list',"goods_id=".$info['goods_id']);	//如果填写的是0库存，删除待清仓列表中的数据
			}
			
        }

	
        $cost_price = $cost_price;
        $clear_goods_json = json_encode($new_arr);
        $updata = array('clear_goods_json' => $clear_goods_json, 'status' => 2
        , "cost_price" => $cost_price, "stock_count" => $stock_count, 'confirm_stock_user' => $_COOKIE['username'], 'confirm_stock_time' => date("Y-m-d H:i:s"));
        $this->db->update('db_goods_clear', $updata, 'id=' . $formdata['dataid']);
        $history_url = $_SERVER['HTTP_REFERER'];
        echo "<script language='javascript'>alert('库存确认成功，已流转至等待清仓状态');location.href='$history_url';</script>";
    }
    /****************-------------调货代码逻辑*------------*/

    //滞销商品
    public function setClear()
    {
        $storeneedid = $this->input->get("dataid");
        $rs = $this->fun->getdatabasesdetail("db_goods_clear", "AND id=" . $storeneedid);
        $needgoods = json_decode($rs['clear_goods_json'], true);
        $this->tpl->assign("goodslist", $needgoods);
        $rs['print_time'] = date("Y-m-d H:i");
        $shop_tpl_data["info"] = $rs;
        $shop_tpl_data['is_finish'] = $rs['action_state'];
        $shop_tpl_data['needstore'] = $needgoods;
        $shop_tpl_data['dataid'] = $storeneedid;
        $printr_info = $this->tpl->fetch('sales/discount.tpl', $shop_tpl_data);
        echo $printr_info;
    }

    public function updateGoodsState()
    {
        $formdata = $this->input->post();

		
        $res = $this->fun->getdatabasesdetail("db_goods_clear", "AND id=" . $formdata['dataid']);
        $cleargoods = json_decode($res['clear_goods_json'], true);
        $new_arr = array();
        $cost_price = $stock_count = 0;
        foreach ($cleargoods as $key => $info) {
            $info['discount'] = $this->input->post("goodsid_" . $info['goods_id']);
			//$info['unsold_discount'] = $this->input->post("unsold_goodsid_" . $info['goods_id']);
			$info['unsold_discount'] = 0;
            $new_arr[] = $info;
        }
        $cost_price = $cost_price;
        $clear_goods_json = json_encode($new_arr);
		
		/****这个值需要单独存储数据表********/
		$post="";
		foreach($new_arr as $key=>$rs)
		{
			$rsdb = $this->fun->getdatabasesdetail("db_goods"," AND goods_id = '".$rs['goods_id']."'");
			$post[$key]["goods_id"] = $rs["goods_id"];
			$post[$key]["parent_id"] = $rs["parent_id"];
			$post[$key]["sku"] = $rs["sku"];
			$post[$key]["goods_name"] = $rs["goods_name"];
			$post[$key]["cost_price"] = $rs["cost_price"];
			$post[$key]["storagename"] = $rs["storagename"];
			$post[$key]["storage_id"] = $rs["storage_id"];
			$post[$key]["stock"] = $rs["stock"];
			$post[$key]["confirmstock"] = $rs["confirmstock"];
			$post[$key]["positions"] = $rs["positions"];
			$post[$key]["discount_price"] = $rs["discount"];
			$post[$key]["unsold_price"] = $rs["unsold_discount"]?$rs["unsold_discount"]:0;
			$post[$key]["buyer"] = $rsdb['g_buyer'];
			$post[$key]["check_man"] = $rsdb['g_checkman'];
			$post[$key]["discount"] = $formdata["discount"];
			$post[$key]["unsolddiscount"] = $formdata["unsolddiscount"]?$formdata["unsolddiscount"]:0;
			$post[$key]["instime"] = time();
			$post[$key]["oper"] = $_COOKIE["username"];
		
		}
		$this->db->insert_batch('db_goods_clear_detail',$post);
	
		
        $updata = array('clear_goods_json' => $clear_goods_json, 'status' => 3, 'discount' => $formdata['discount']
        , 'set_discount_user' => $_COOKIE['username'], 'set_discount_time' => date("Y-m-d H:i:s"));
        $this->db->update('db_goods_clear', $updata, 'id=' . $formdata['dataid']);

		//删除待清仓列表中的数据
		foreach($new_arr as $key=>$info)
		{
			$this->db->delete('db_goods_clear_list',"goods_id=".$info['goods_id']);	//删除待清仓列表中的数据
		}
		$this->changcosprice($new_arr,$formdata['discount']);
       

        $history_url = $_SERVER['HTTP_REFERER'];
        echo "<script language='javascript'>alert('商品关联价与销售状态已更新，清仓处理功能');location.href='$history_url';</script>";
    }

    public function changcosprice($skulist,$discount)
    {
	
        //清仓的商品修改半价成本
        foreach ($skulist as $key => $rs) {
			$rsGoods = $this->db->get_one("SELECT goods_id,goods_sku,goods_name,g_sale_status,g_costprice,bulkprice,goods_parentID,
            goods_parent_sku from db_goods  where goods_id = '" . $rs['goods_id'] . "'");
			$bulkprice = intval($rsGoods["bulkprice"] * ($discount/100));
			$costprice = intval($rsGoods["g_costprice"] * ($discount/100));
			$isbulk = "";
			$contentstr="";
			$stock_str = "";
			$price_str="";
			if($rsGoods["bulkprice"] != $bulkprice)
			{
				$isbulk = $rsGoods["bulkprice"];
				$contentstr="原关联价[{$rsGoods[bulkprice]}]修改成[$bulkprice],";
			}
			if($rs["stock"] != $rs['confirmstock'])
			{
				$stock_str  = "将{$rs[storagename]}库存[$rs[stock]]更新为[{$rs[confirmstock]}]";
			}
			if($rsGoods["g_costprice"] != $costprice)
			{
				$price_str  = "原成本价[{$rsGoods[g_costprice]}]修改成[{$costprice}]";
			}
			$content = "销售状态为[清仓] {$contentstr} {$price_str} {$stock_str}";
            $this->fun->goods_update_log($rsGoods["goods_id"], $content, 1);
			$this->db->update("db_goods_stock", array("stock" => $rs["confirmstock"]), "storage_id={$rs[storage_id]} and goods_id=" . $rsGoods["goods_id"]);
			$this->db->update("db_goods", array("bulkprice" => $bulkprice,"g_costprice"=> $costprice, "g_sale_status" => 5), "goods_id=" . $rsGoods["goods_id"]);
		
				/***存清仓之前的价格***/
			$postdb="";
			$postdb['p_parent_id'] = $rsGoods["goods_id"];
			$postdb['p_parent_sku'] =$rsGoods["goods_sku"];
			$postdb['type'] =2;
			if($rsGoods["g_supplier"] ==1 || $rsGoods['g_supplier'] ==2)
			{
				$postdb['reason'] =$rsGoods["bulkprice"];
			}else{
				$postdb['reason'] =$rsGoods["g_costprice"];	
			}
			$postdb['descr'] =$content;
			$postdb['createUser'] =$_COOKIE['username'];
			$postdb['createUid'] =$_COOKIE['userid'];
			$postdb['addTime'] =date("Y-m-d H:i:s");
			$this->db->insert('db_goods_status',$postdb);
				/***存盘点***/
			if($rs["stock"] != $rs['confirmstock'])
			{
				$post="";
				$post['goods_id'] = $rsGoods["goods_id"];
				$post['goods_name'] = $rsGoods['goods_name'];
				$post['oldnum'] = $rs["stock"];
				$post['newnum'] = $rs["confirmstock"];
				$post['goods_sku'] = $rsGoods['goods_sku'];
				$post['goods_instock'] = $rs["confirmstock"];
				$post['tostock'] = $rs["storage_id"];
				$post['storagename'] = $rs["storagename"];
				$post['intime'] = time();
				$post['oper'] = $_COOKIE["userid"];
				$post['opername'] = $_COOKIE["username"];
				$post['memo'] = "";
				$this->db->insert('db_goods_inventory',$post);
			}
			//将主SKU标为清仓
			$this->db->update("db_goods_parent", array("p_sale_status" => 5), "p_parent_id=" . $rsGoods["goods_parentID"]);
			$this->fun->insertsysstatistical('status',5,$rsGoods['goods_id'],0);	//设置清仓提醒
		}
    }

    public function clearGoodsDetail()
    {
        $storeneedid = $this->input->get("dataid");
        $rs = $this->fun->getdatabasesdetail("db_goods_clear", "AND id=" . $storeneedid);
        $needgoods = json_decode($rs['clear_goods_json'], true);
		foreach($needgoods as $key=>$val)
		{
			$needgoods[$key]["stcostprice"] = sprintf("%01.2f", $val['cost_price'] * $val['stock']);
		}
        $this->tpl->assign("goodslist", $needgoods);
        $rs['print_time'] = date("Y-m-d H:i");
        $shop_tpl_data["info"] = $rs;
        $shop_tpl_data['is_finish'] = $rs['action_state'];
        $shop_tpl_data['needstore'] = $needgoods;
        $shop_tpl_data['dataid'] = $storeneedid;

        $cost_price = $stock_count = 0;
        foreach ($needgoods as $key => $info) {
            $cost_price += $info['discount'] * $info['confirmstock'];
        }
        $shop_tpl_data['discount_price'] = $cost_price;
        $printr_info = $this->tpl->fetch('sales/clearGoodsDetail.tpl', $shop_tpl_data);

        echo $printr_info;
    }

    public function goodsClear()
    {
        //dump($_POST);
        $goods_ids = $_POST['storeid'];
        $limit_month = $_POST['limit_month'];
        $unsalelilv = $_POST['unsalelilv'];

        if (count($goods_ids) > 0) {
            $goods_ids_str = implode(',', $goods_ids);
            if (!empty($goods_ids)) {
                $where .= " && B.goods_id in(" . $goods_ids_str . ")";
            }
        }

		$where.=" and A.stock >0 AND A.storage_id in(1,2) ";
        $limit_month_time = strtotime("-$limit_month month");
        if (!empty($unsalelilv)) {
           // $where .= " && A.stock/B.newnum >0." . $unsalelilv;
        }
        //dump($_POST);
		/*
        $where .= " && B.goods_id not in(select distinct goods_id from db_goods_handstorage where intime>$limit_month_time and  id is not null)";
        $tpl_data = array("sch_namecn" => $search_data['sch_namecn'], 'sch_name' => $search_data['sch_name'], 'limit_month' => $limit_month,
            'imit_month_date' => date("Y-m-d", $limit_month_time), 'starttime' => $starttime, 'endtime' => $endtime, 'search_sku' => $search_sku,
            'message_state' => $search_data['message_state'], 'unsalelilv' => $unsalelilv);
        $list = $this->fun->getalllist("db_goods_handstorage B left join db_goods_stock A on A.goods_id=B.goods_id and A.storage_id=B.tostock",
            $where, $nowpage, 0, $this->pageSize, ' group by B.goods_id order by B.intime desc', "*,
        A.stock/B.newnum as unsalelilv");*/

		  $list = $this->fun->getalllist("db_goods_stock A LEFT JOIN db_goods B on A.goods_id=B.goods_id ",
            $where, $nowpage, 0, $this->pageSize, ' group by B.goods_id order by B.goods_id desc', "*,A.storage_name as storagename");
			$datalist = $list["list"];

//        $sku_list = iarray_column($datalist, 'goods_sku');
//        $sku_list_str = implode("','", $sku_list);
//        $goods_list = $this->fun->getdatabaseslist("db_goods", " and goods_sku in('$sku_list_str')", "goods_id,goods_sku,g_costprice,bulkprice");
//        $costprice_list = iarray_column($goods_list, 'g_costprice', 'goods_id');
//	
        $save_json_arr = array();
        foreach ($datalist as $key => $val) {
            $datalist[$key]['insttime'] = date("Y-m-d", $val['intime']);
            $datalist[$key]['unsalelilv'] = round($val['unsalelilv'] * 100, 2);
				
			if($val['g_supplier'] ==1 || $val['g_supplier'] ==2)
			{
				 $costprice = $val['bulkprice']?$val['bulkprice']:$val['g_costprice'];
			}else{
				 $costprice =$val['g_costprice'];
			}


			$datalist[$key]['bulkpricecostprice'] = $costprice;
            $datalist[$key]['costprice'] = sprintf("%01.2f", $costprice * $val['stock']);
            $clearGoodinfo = array("goods_id" => $val['goods_id'],
            'parent_id'=>$val['goods_parentID'],
             "sku" => $val['goods_sku'], "goods_name" => $val['goods_name'], 'cost_price' => $costprice,
                "storagename" => $val['storagename'], "storage_id" => $val['storage_id'], "stock" => $val['stock'], "confirmstock" => $val['stock'], 'positions' => $val['positions']);
            $save_json_arr[] = $clearGoodinfo;
        }
        $this->tpl->assign("save_json", json_encode($save_json_arr));
        $this->tpl->assign("datalist", $datalist);
        $this->tpl->display("sales/goodsClear.tpl");
    }

    public function delClearInfo()
    {
        $storeneed = $this->input->get("infoid");
		
		$rs = $this->fun->getdatabasesdetail("db_goods_clear", "AND id=" . $storeneed);
        $needgoods = json_decode($rs['clear_goods_json'], true);
		foreach($needgoods as $key=>$val)
		{
			$this->db->update("db_goods_clear_list",array('types'=>0),"goods_id='".$val['goods_id']."'");
		}
        $this->db->delete('db_goods_clear', 'id=' . $storeneed);
        $history_url = $_SERVER['HTTP_REFERER'];
        echo "<script language='javascript'>location.href='" . $history_url . "';</script>";
    }

    public function storageList()
    {
        $this->tpl->display("sales/storageList.tpl");
    }

    public function editProgram()
    {
        $id = $this->input->get('id');
        $this->addprogram($id);
    }

    public function addProgramProducts()
    {
        $postdata = $this->input->post();
        $program_id = $postdata['program_id'];
        $skulist = explode("\n", trim($_POST['sku']));
        foreach ($skulist as $key => $val) {
            if (trim($val) == '') {//去掉空行
                unset($skulist[$key]);
                continue;
            }
            $skulist[$key] = trim($val);
        }
        $sku_strs = implode("','", $skulist);
        $sku_strs = "'" . $sku_strs . "'";
        $sku_list = $this->fun->getalllist("db_goods", " and goods_sku in($sku_strs)", null, 0, 0, ' order by goods_id desc', 'goods_id,goods_name,g_costprice,goods_sku');
        $sku_arr = $exists_sku = array();
        foreach ($sku_list['list'] as $key => $sku_info) {
            $sku_arr[] = array('goods_sku' => $sku_info['goods_sku'], 'goods_id' => $sku_info['goods_id']);//存储正确的sku编号
            $exists_sku[] = $sku_info['goods_sku'];
        }
        //去除重复新增的sku编号
        $havs_insert_sku = $this->fun->getalllist("db_sales_goods", " and sku_code in($sku_strs) && program_id=$program_id", null, 0, 0, '', 'id,sku_code');
        $insert_skulist = array();
        foreach ($havs_insert_sku['list'] as $key => $sku_info) {
            $insert_skulist[] = $sku_info['sku_code']; //存储正确的sku编号
        }
        foreach ($skulist as $key => $val) {
            if (!in_array($val, $exists_sku)) {//存错误的sku
                $err_sku .= $val . "，";
            }
        }
        $havs_insert_sku_str = '';
        foreach ($sku_list['list'] as $key => $val) {
            if (in_array($val['goods_sku'], $insert_skulist)) {//去掉重复的sku
                $havs_insert_sku_str .= $val['goods_sku'] . "，";
                unset($sku_list['list'][$key]);
            }
        }

        if (count($sku_arr) > 0) {//有正确的sku执行新增
            $insert_ret = $this->m->addProgramProduct($sku_arr, $postdata['program_id']);
            $ret_state = 1;
        } else {
            $ret_state = 0;
        }
        $history_url = $_SERVER['HTTP_REFERER'];
        $ret_data = array('err_sku' => $err_sku, 'success_sku' => $sku_list['list'],
            'havs_insert_sku' => $havs_insert_sku_str, 'sku_str' => $sku_strs, 'history_url' => $history_url);
        $this->tpl->assign($ret_data);
        $this->tpl->display("sales/addproduct.tpl");
    }

    public function changeStockList()
    {
        header("Content-type: text/html; charset=utf-8");
        $all_goods_id = array();
        $where = " and storage_name='二号仓' and stock>=1";
        $goods_list = $this->fun->getalllist('db_goods_stock', $where, 1, 0, 20000, ' order by goods_id desc');
        $all_goods_id = iarray_column($goods_list['list'], 'goods_id');


        $this->load->model('Product_m', 'product_mod');

        $all_goods_id_str = implode(",", $all_goods_id);
        $where = " and a.goods_id in($all_goods_id_str) and storage_id in(1,2)";
        $goods_list = $this->fun->getalllist('db_goods a left join db_goods_stock b on b.goods_id=a.goods_id ', $where, 1, 0, 20000,
            'order by a.goods_id desc', "b.*,a.goods_id,a.goods_sku,a.goods_name,a.dailysales");

        $newgoods = array();
        foreach ($goods_list['list'] as $key => $goodinfo) {
            $goodinfo['day_salys'] = round($goodinfo['dailysales'] * 3);
            $newgoods[$goodinfo['goods_id'] . "_" . $goodinfo['storage_id']] = $goodinfo;
        }
        //dump($newgoods);
        $shipping_status = 5;
        $have_send_sql = "SELECT sum(goods_number) as goods_number,goods_id FROM db_order_sell A left join db_order_list B
        on A.`order_id` = B.order_id where A.`goods_id` in($all_goods_id_str) AND B.order_status in (2,3)
         and B.shipping_status = $shipping_status and is_nodelivery = 0 group by goods_id";
        $res = $this->db->query($have_send_sql);
        $have_send = $res->result_array();
        //dump($have_send);
        $have_send_arr = iarray_column($have_send, 'goods_number', 'goods_id');
        //dump($have_send_arr);
        //echo $this->db->last_query();
        $success_goods = array();
        foreach ($newgoods as $key => $info) {
            if ($info['storage_id'] == '2') {
                continue;
            }
            //$sendgoodsnum = $this->product_mod->getsendthegoods($info['goods_id'],$info['storage_id']);
            $sendgoodsnum = $have_send_arr[$info['goods_id']];
            $infov['storage_name'] = '2';
            $info['two_storage_name'] = $newgoods[$info['goods_id'] . "_" . $infov['storage_name']]['storage_name'];
            $info['two_stock'] = $newgoods[$info['goods_id'] . "_" . $infov['storage_name']]['stock'];
            $info['two_stockid'] = $newgoods[$info['goods_id'] . "_" . $infov['storage_name']]['id'];
            $info['two_positions'] = $newgoods[$info['goods_id'] . "_" . $infov['storage_name']]['positions'];
            $info['sendgoodsnum'] = $sendgoodsnum;
            $stock = $info['stock'] < 0 ? 0 : $info['stock'];
            $needstore = $sendgoodsnum - $stock > $info['two_stock'] ? $info['two_stock'] : $sendgoodsnum - $stock;
            $needstore = $needstore + $info['day_salys'] > $info['two_stock'] ? $info['two_stock'] : $needstore + $info['day_salys'];
            $info['needstore'] = $needstore;
            //$info['sendgoodsnum']+=$info['day_salys'];
            if ($info['sendgoodsnum'] > $info['stock'] && $info['sendgoodsnum'] > 0 && $info['two_stock'] > 0 or ($needstore > $info['stock'] && $needstore > 0)) {
                $success_goods[] = $info;
            }
        }
        //dump($success_goods);
        $this->tpl->assign("total", count($success_goods));
        $this->tpl->assign("datalist", $success_goods);
        $this->tpl->display("StoreManage/changeStockList.tpl");

        //dump($success_goods);
    }

    public function storeNeedList()
    {
        $nowpage = $_REQUEST["pageid"];
        if ($nowpage == "") $nowpage = 1;
        $this->tpl->assign($tpl_data);
        if (!empty($search_data['sch_namecn'])) {
            $where .= " && namecn='" . $search_data['sch_namecn'] . "'";
        }
        if (!empty($search_data['sch_name'])) {
            $where .= " && name='" . $search_data['sch_name'] . "'";
        }
        $tpl_data = array("sch_namecn" => $search_data['sch_namecn'], 'sch_name' => $search_data['sch_name'],
            'starttime' => $starttime, 'endtime' => $endtime, 'message_state' => $search_data['message_state']);
        $list = $this->fun->getalllist("db_store_change", $where, $nowpage, $if_csv, $this->pageSize, " order by id desc");
        $pageList = $this->pagenav->page($list["total"], $nowpage, $this->pageSize);
        $this->tpl->assign($tpl_data);
        $this->tpl->assign("totalpage", ceil($list["total"] / $this->pageSize));
        $this->tpl->assign("total", $list["total"]);
        $this->tpl->assign("pageList", $pageList);
        $this->tpl->assign("datalist", $list["list"]);

        $this->tpl->display("StoreManage/storeNeedList.tpl");
    }

    public function goodsClearList()
    {
        $nowpage = $_REQUEST["pageid"];
        if ($nowpage == "") $nowpage = 1;
        if (!empty($search_data['sch_namecn'])) {
            $where .= " && namecn='" . $search_data['sch_namecn'] . "'";
        }
        if (!empty($search_data['sch_name'])) {
            $where .= " && name='" . $search_data['sch_name'] . "'";
        }
        $tpl_data = array("sch_namecn" => $search_data['sch_namecn'], 'sch_name' => $search_data['sch_name'],
            'starttime' => $starttime, 'endtime' => $endtime, 'message_state' => $search_data['message_state']);
        $list = $this->fun->getalllist("db_goods_clear", $where, $nowpage, $if_csv, $this->pageSize, " order by id desc");
        $tpl_data['status'] = array('', '等待盘点', '等待清仓设置', '清仓设置完成');
        $pageList = $this->pagenav->page($list["total"], $nowpage, $this->pageSize);
        $this->tpl->assign($tpl_data);
        $this->tpl->assign("totalpage", ceil($list["total"] / $this->pageSize));
        $this->tpl->assign("total", $list["total"]);
        $this->tpl->assign("pageList", $pageList);
        $this->tpl->assign("datalist", $list["list"]);
		
		if($this->config->item('sys_goodsClear')){
			 $sys_goodsClear = explode("|",$this->config->item('sys_goodsClear'));
			 if(in_array($_COOKIE["username"],$sys_goodsClear))
			 {
				 $this->tpl->assign("sys_goodsClear",1);
			 }else{
				 $this->tpl->assign("sys_goodsClear",0);
			 }
		}
		if($this->config->item('sys_goodsClear_check')){
			 $sys_goodsClear_check = explode("|",$this->config->item('sys_goodsClear_check'));
			 if(in_array($_COOKIE["username"],$sys_goodsClear_check))
			 {
				 $this->tpl->assign("sys_goodsClear_check",1);
			 }else{
				 $this->tpl->assign("sys_goodsClear_check",0);
			 }
		}
		if($this->config->item('sys_goodsClear_inventory')){
			 $sys_goodsClear_inventory = explode("|",$this->config->item('sys_goodsClear_inventory'));
			 if(in_array($_COOKIE["username"],$sys_goodsClear_inventory))
			 {
				 $this->tpl->assign("sys_goodsClear_inventory",1);
			 }else{
				 $this->tpl->assign("sys_goodsClear_inventory",0);
			 }
			
		}

        $this->tpl->display("sales/goodsClearList.tpl");
    }
}
